<template>
  <div class="product-type-management">
    <div class="management-content">
      <!-- 搜索区域 -->
      <div class="search-container">
        <el-input
          v-model="searchQuery"
          placeholder="请输入产品类型名称搜索"
          class="search-input"
          @input="handleSearch"
        />
        <!-- 将新增产品类型按钮移到搜索区域 -->
        <el-button type="primary" class="primary-button" @click="showAddDialog">新增产品类型</el-button>
      </div>
      
      <!-- 表格区域 -->
      <el-table :data="filteredProductTypes" fit v-loading="loading">
        <el-table-column prop="id" label="ID" width="80" header-align="center" align="center" />
        <el-table-column prop="cnName" label="产品类型中文" width="150" header-align="center" align="center" />
        <el-table-column prop="enName" label="产品类型英文" min-width="150" header-align="center" align="center" />
        <el-table-column prop="comment" label="描述" min-width="200" show-overflow-tooltip header-align="center" />
        <el-table-column prop="createdTime" label="创建时间" min-width="160" header-align="center" align="center" />
        <el-table-column prop="createdBy" label="创建人" min-width="100" header-align="center" align="center" />
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button type="primary" size="small" @click="editProductType(scope.row)">编辑</el-button>
            <el-button type="danger" size="small" @click="deleteProductType(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 新增/编辑产品类型对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle">
      <el-form ref="formRef" :model="formData" label-width="100px">
        <el-form-item label="英文名称" prop="enName" :rules="[{ required: true, message: '请输入英文名称', trigger: 'blur' }]">
          <el-input v-model="formData.enName" placeholder="请输入英文名称" />
        </el-form-item>
        <el-form-item label="中文名称" prop="cnName" :rules="[{ required: true, message: '请输入中文名称', trigger: 'blur' }]">
          <el-input v-model="formData.cnName" placeholder="请输入中文名称" />
        </el-form-item>
        <el-form-item label="备注" prop="comment">
          <el-input v-model="formData.comment" type="textarea" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessageBox } from 'element-plus'
import notificationService from '../utils/notificationService.js'
import { productTypeAPI } from '../api/productType.js'

const productTypes = ref([])
const searchQuery = ref('')
const dialogVisible = ref(false)
const dialogTitle = ref('新增产品类型')
const formData = reactive({
  id: '',
  enName: '',
  cnName: '',
  comment: ''
})
const formRef = ref()
const loading = ref(false)
// 分页相关数据
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 处理搜索输入
const handleSearch = () => {
  // 搜索时重置到第一页
  currentPage.value = 1
  fetchProductTypes()
}

// 过滤产品类型列表
const filteredProductTypes = computed(() => {
  let filtered = productTypes.value
  
  // 搜索过滤
  if (searchQuery.value) {
    filtered = filtered.filter(item => 
      item.cnName.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
      item.comment.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
      item.enName.toLowerCase().includes(searchQuery.value.toLowerCase())
    )
  }
  
  // 分页处理
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  
  return filtered.slice(start, end)
})

// 处理页码变化
const handleCurrentChange = (current) => {
  currentPage.value = current
  fetchProductTypes()
}

// 处理每页条数变化
const handleSizeChange = (size) => {
  pageSize.value = size
  // 重置到第一页
  currentPage.value = 1
  fetchProductTypes()
}

// 获取产品类型列表
const fetchProductTypes = async () => {
  loading.value = true
  try {
    const response = await productTypeAPI.getProductTypes({
      pageSize: pageSize.value,
      currentPage: currentPage.value,
      searchKey: searchQuery.value
    })
    // 从API响应中正确提取数据 (根据新的返回参数结构，数据在data.records中)
    productTypes.value = response.data?.records || []
    // 更新总条数
    total.value = response.data?.total || 0
  } catch (error) {
    // 使用后端返回的错误信息或默认错误提示
    const errorMessage = error.response?.data?.message || error.message || '获取产品类型列表失败'
    notificationService.error(errorMessage)
    console.error('获取产品类型列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 显示新增对话框
const showAddDialog = () => {
  dialogTitle.value = '新增产品类型'
  Object.assign(formData, {
    id: '',
    enName: '',
    cnName: '',
    comment: ''
  })
  dialogVisible.value = true
}

// 编辑产品类型
const editProductType = (row) => {
  dialogTitle.value = '编辑产品类型'
  Object.assign(formData, row)
  dialogVisible.value = true
}

// 提交表单
const submitForm = async () => {
  if (!formData.enName || !formData.cnName) {
    // 这里不需要前端提示，因为在表单验证中已经处理
    return
  }
  
  loading.value = true
  try {
    if (formData.id) {
      // 编辑操作
      await productTypeAPI.updateProductType(formData.id, formData)
      notificationService.success('产品类型更新成功')
    } else {
      // 新增操作
      await productTypeAPI.createProductType(formData)
      notificationService.success('产品类型添加成功')
    }
    // 重新获取列表
    await fetchProductTypes()
    dialogVisible.value = false
  } catch (error) {
    // 使用后端返回的错误信息或默认错误提示
    const errorMessage = error.response?.data?.message || error.message || (formData.id ? '更新产品类型失败' : '添加产品类型失败')
    notificationService.error(errorMessage)
    console.error('操作失败:', error)
  } finally {
    loading.value = false
  }
}

// 删除产品类型
const deleteProductType = async (id) => {
  ElMessageBox.confirm('确定要删除这个产品类型吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    loading.value = true
    try {
      await productTypeAPI.deleteProductType(id)
      notificationService.success('删除成功')
      // 重新获取列表
      await fetchProductTypes()
    } catch (error) {
    // 使用后端返回的错误信息或默认错误提示
    const errorMessage = error.response?.data?.message || error.message || '删除失败'
    notificationService.error(errorMessage)
    console.error('删除失败:', error)
  } finally {
      loading.value = false
    }
  }).catch(() => {
    notificationService.info('已取消删除')
  })
}

// 组件挂载时获取数据
onMounted(() => {
  fetchProductTypes()
})


</script>

<style scoped>
.product-type-management {
  position: relative;
  padding: 0;
  background: white;
  overflow: hidden;
}

.management-content {
  position: relative;
  z-index: 1;
  width: 100%;
  box-sizing: border-box;
  background: white;
  min-height: calc(100vh - 130px);
  display: flex;
  flex-direction: column;
}

.search-container {
  display: flex;
  gap: 15px;
  padding: 20px 24px;
  align-items: center;
  flex-wrap: wrap;
  width: 100%;
  box-sizing: border-box;
  border-bottom: 1px solid #ebeef5;
  justify-content: space-between;
}

.search-input {
  width: 280px;
  max-width: 100%;
}

.primary-button {
  background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
  border: none;
  color: white;
  transition: all 0.3s ease;
}

.primary-button:hover {
  background: linear-gradient(90deg, #5a67d8 0%, #6b46c1 100%);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

/* 搜索框样式 */
:deep(.el-input__wrapper) {
  border-radius: 8px;
  background: rgba(255, 255, 255, 0.8);
}

:deep(.el-input__wrapper:hover) {
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.2);
}

/* 表格样式 - 添加完整边框并调整内边距 */
:deep(.el-table) {
  --el-table-header-bg-color: rgba(102, 126, 234, 0.1);
  --el-table-header-text-color: #667eea;
  width: calc(100% - 40px);
  flex: 1;
  margin: 0 20px;
  background: white;
  border: 1px solid #ebeef5;
  border-radius: 0;
  --el-table-border-color: #ebeef5;
  --el-table-row-hover-bg-color: rgba(102, 126, 234, 0.05);
}

/* 确保表格头部颜色完全填充 */
:deep(.el-table__header-wrapper) {
  width: 100% !important;
  border-radius: 0;
  border-right: 1px solid #ebeef5;
}

:deep(.el-table__header) {
  width: 100% !important;
  border-radius: 0;
}

/* 表格主体区域边框 */
:deep(.el-table__body-wrapper) {
  border-right: 1px solid #ebeef5;
}

/* 表格单元格边框 */
:deep(.el-table__row td.el-table__cell) {
  border-right: 1px solid #ebeef5;
  border-bottom: 1px solid #ebeef5;
}

/* 表格头部单元格边框 */
:deep(.el-table__header th.el-table__cell) {
  background-color: rgba(102, 126, 234, 0.1) !important;
  padding: 12px 0;
  text-align: center;
  border-right: 1px solid #ebeef5;
  border-bottom: 1px solid #ebeef5;
}

/* 覆盖Element UI默认样式，确保右侧固定列也有边框 */
:deep(.el-table__fixed-right) {
  box-shadow: none !important;
  border-left: 1px solid #ebeef5;
}

/* 确保最后一行也有底边框 */
:deep(.el-table__row:last-child td.el-table__cell) {
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-table__row) {
  transition: background-color 0.2s ease;
}

:deep(.el-table__row:hover) {
  background-color: rgba(102, 126, 234, 0.05);
}

/* 分页样式 */
.pagination-container {
  padding: 20px 24px 20px calc(24px + 20px);
  border-top: 1px solid #ebeef5;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

:deep(.el-pagination) {
  --el-pagination-button-bg-color: rgba(255, 255, 255, 0.8);
  --el-pagination-button-hover-bg-color: rgba(102, 126, 234, 0.1);
  --el-pagination-button-active-bg-color: #667eea;
  --el-pagination-button-active-color: white;
}

/* 对话框样式 */
:deep(.el-dialog__header) {
  background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
  border-radius: 8px 8px 0 0;
}

:deep(.el-dialog__title) {
  color: white;
  font-weight: bold;
}

:deep(.el-dialog__close) {
  color: white;
}

:deep(.el-dialog__body) {
  padding: 24px;
  background: white;
}

:deep(.el-dialog__footer) {
  padding: 16px 24px;
  background: #f9f9fa;
  border-radius: 0 0 8px 8px;
}

/* 表单样式 */
:deep(.el-form-item__label) {
  font-weight: 500;
  color: #303133;
}

/* 对话框样式优化 */
.el-dialog {
  max-width: 90vw;
  margin: 20px auto;
  width: auto !important;
}

/* 响应式设计 */
@media screen and (max-width: 768px) {
  .product-type-management {
    padding: 10px;
  }
  
  .management-content {
    padding: 16px;
  }
  
  .search-container {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-input {
    width: 100%;
    margin-bottom: 12px;
  }
  
  .primary-button {
    width: 100%;
  }
  
  :deep(.el-table) {
    width: calc(100% - 20px);
    margin: 0 10px;
  }
  
  .pagination-container {
    padding: 16px 16px 16px calc(16px + 10px);
    justify-content: center;
  }
}
</style>